package com.chianghao.rockframewrok.starter.authentication;


import com.chianghao.rockframewrok.auth.cache.IAuthCache;
import com.chianghao.rockframewrok.auth.cache.impl.LocalAuthCacheImpl;
import com.chianghao.rockframewrok.auth.core.token.ITokenCache;
import com.chianghao.rockframewrok.auth.core.token.ITokenHandle;
import com.chianghao.rockframewrok.auth.core.token.impl.JWTTokenHandleImpl;
import com.chianghao.rockframewrok.auth.core.token.impl.TokenCacheImpl;
import com.chianghao.rockframewrok.auth.core.token.model.Token;
import com.chianghao.rockframewrok.auth.web.filter.AuthFilter;
import com.chianghao.rockframewrok.starter.authentication.properties.AuthProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@EnableConfigurationProperties({AuthProperties.class})
@Configuration
public class AuthConfiguration {


	@Autowired
	AuthProperties authProperties;
	
	@Bean
	@ConditionalOnMissingBean(IAuthCache.class)
	public IAuthCache authCache() {
		return new LocalAuthCacheImpl();
	}
	
	
	@Bean
	@ConditionalOnMissingBean(ITokenCache.class)
	public ITokenCache tokenCache() {
		return new TokenCacheImpl();
	}
	
	
	@Bean
	@ConditionalOnMissingBean(ITokenHandle.class)
	public JWTTokenHandleImpl tokenHandle(ITokenCache tokenCache) {
		JWTTokenHandleImpl jh = JWTTokenHandleImpl.get(tokenCache);
		return jh;
	}
	
	

	@Bean
	public FilterRegistrationBean<AuthFilter> delegatingFilter(IAuthCache authCache, ITokenHandle<? extends Token> tokenHandle) {
		FilterRegistrationBean<AuthFilter> bean = new FilterRegistrationBean<AuthFilter>();
		AuthFilter filter  = new AuthFilter(authCache,tokenHandle);
		//filter
		bean.setFilter(filter);
		bean.addInitParameter("outTime", String.valueOf(authProperties.getTokenOutTime()));
		bean.addInitParameter("AuthContentTypeName", authProperties.getAuthContentTypeName());
		//filter name
		bean.setName("autoFile");
		//filter path
		bean.addUrlPatterns(authProperties.getUrlPatterns());
		bean.setOrder(2);
		return bean;
	}

	
	
	

	
}
